#include "UdpServer.hpp"
#include <iostream>
#include <memory>
#include <cstdio>
#include <vector>
bool check_cmd(const std::string& cmd)
{
    std::vector<std::string> ForbiddenOrders = {
        "rm",
        "cp",
        "mv",
        "top",
        "yum",
        "uninstall",
        "while",
        "sleep"
    };
    for(auto& str : ForbiddenOrders)
    {
        if(cmd.find(str) != std::string::npos)
            return false;
    }
    return true;
}
std::string ExcuteCommand(const std::string &cmd)
{
    std::cout << "get a request message" << cmd << std::endl;
    if(!check_cmd(cmd))
    {
        return "you are a bad man";
    }
    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == nullptr)
    {
        perror("popen fail");
        return "error";
    }
    std::string result;
    char buffer[4096];
    memset(buffer, 0, sizeof(buffer));
    while (true)
    {
        char *res = fgets(buffer, sizeof(buffer), fp);
        if(res == nullptr)  break;
        result += buffer;
    }
    pclose(fp);

    return result;
}
std::string Handler(const std::string &str, const std::string& clientip, uint16_t clientport)
{
    std::string peoinfo = "[";
    peoinfo += clientip;
    peoinfo += ":";
    peoinfo += std::to_string(clientport);
    peoinfo += "]#";
    std::cout << peoinfo << std::endl;
    std::string res = "server get a message:";
    res += str;
    std::cout << res << std::endl;
    return res;
}
int main()
{
    std::unique_ptr<UdpServer> udpserver(new UdpServer);
    udpserver->Init();
    udpserver->Run(Handler);
    return 0;
}